package com.alibaba.algo.utils;

import lombok.extern.java.Log;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.*;

@Log
public class XMLUtil {

    public static String covertObjToXML(Object t) {
        StringWriter sw = new StringWriter();
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(t.getClass());
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(t, sw);
        } catch (JAXBException e) {
            log.info("xml covert exception " + e.getMessage());
            throw new RuntimeException("object cannot convert to xml");
        }
        return sw.toString();
    }

    public static Object covertXmlToObject(Object object, MultipartFile file) {
        try {
            JAXBContext context = JAXBContext.newInstance(object.getClass());
            Unmarshaller unmarshaller = context.createUnmarshaller();
            return unmarshaller.unmarshal(file.getInputStream());
        } catch (JAXBException | IOException e) {
            throw new RuntimeException("import file error");
        }
    }

}
